package com.example.venue_reservation_service.utils;

import okhttp3.*;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.IOException;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 学校身份信息认证（优化版）
 */
public class IdentityUtil {

    // 向量
    private final static String iv = "01234567";
    // 加解密统一使用的编码方式
    private final static String encoding = "utf-8";
    // 密钥
    private final static String pk = "08192ec57d80193b9fa4b9a0";
    // 请求路径
    private static final String PATH = "http://dcpint.ecjtu.edu.cn/unis/IfsDcpIntPortalServlet";
    // OkHttpClient实例
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(3, TimeUnit.SECONDS)
            .build();

    /**
     * 3DES加密方法
     */
    public static String desEncode(String plainText) throws Exception {
        DESedeKeySpec spec = new DESedeKeySpec(pk.getBytes());
        SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("desede");
        Key deskey = keyfactory.generateSecret(spec);

        Cipher cipher = Cipher.getInstance("desede/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(iv.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);

        byte[] encryptData = cipher.doFinal(plainText.getBytes(encoding));
        return bytesToHexString(encryptData);
    }

    /**
     * 字节数组转十六进制字符串
     */
    private static String bytesToHexString(byte[] b) {
        StringBuilder ret = new StringBuilder();
        for (byte value : b) {
            String hex = Integer.toHexString(value & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            ret.append(hex.toUpperCase());
        }
        return ret.toString();
    }

    /**
     * 发送HTTP POST请求
     */
    public static String httpPostRequest(Map<String, String> params) {
        if (params == null || params.isEmpty()) {
            return "-1";
        }

        FormBody.Builder formBuilder = new FormBody.Builder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            try {
                formBuilder.add(entry.getKey(), entry.getValue());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        Request request = new Request.Builder()
                .url(PATH)
                .post(formBuilder.build())
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                return response.body().string();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "-1";
    }

    /**
     * 获取教职工信息列表（优化版）
     * @param phoneNumber 手机号码（对应原参数中的SJHM）
     * @return API返回结果字符串
     */
    public static String getGzzxList(String phoneNumber) throws Exception {
            String param = "<param>"
                    + "<module>IcdcShare</module>"
                    + "<method>getJzgjcxx2</method>"
                    + "<params>SJHM=" + phoneNumber + "</params>"
                    + "</param>";

            String encryptedParam = desEncode(param);

            Map<String, String> params = new HashMap<>();
            params.put("clienttype", "java");
            params.put("name", "cgyy_dcpint_getJbxx");
            params.put("param", encryptedParam);
            return httpPostRequest(params);

    }
}